package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.models.auth.In;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;
import java.time.LocalDateTime;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /*@Autowired
    private HttpServletRequest request;    //拿到token

    @Autowired
    private JwtProperties jwtProperties;   //拿到jwt密钥*/


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }

    /**
     * 分页查询员工
     */
    @Override
    public PageResult getEmployeeByPage(EmployeePageQueryDTO epqd) {
        PageHelper.startPage(epqd.getPage(), epqd.getPageSize());
        Page<Employee> p = employeeMapper.getEmployeeByPage(epqd.getName());
        PageResult pr =new PageResult();
        pr.setTotal(p.getTotal());
        pr.setRecords(p.getResult());
        return pr;
    }

    /**
     * 新增员工
     */
    @Override
    public void insertEmployee(EmployeeDTO ed) {
//        Employee e = employeeMapper.getByUsername(ed.getUsername());  //判断用户名是否存在，交给全局异常处理
        /*String token = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);  //拿到载荷数据*/
        Long empId = BaseContext.getCurrentId();
        Employee employee = new Employee();
        BeanUtils.copyProperties(ed, employee);    //将左边同名同类型的属性拷贝到右边对象
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);
        employee.setCreateUser(empId);*/
        /*employee.setUpdateUser(claims.get("empId",Long.class));
        employee.setCreateUser(claims.get("empId",Long.class));*/
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setStatus(StatusConstant.ENABLE);
        /*Employee employee = Employee.builder()
                .username(ed.getUsername())
                .name(ed.getName())
                .password(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()))
                .phone(ed.getPhone())
                .sex(ed.getSex())
                .idNumber(ed.getIdNumber())
                .status(StatusConstant.ENABLE)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .createUser(claims.get("empId",Long.class))
                .updateUser(claims.get("empId",Long.class))
                .build();*/
        employeeMapper.insertEmployee(employee);

    }

    /**
     *根据id查询员工接口
     */
    @Override
    public Employee getById(Long id) {
        Employee e = employeeMapper.getById(id);
        return e;
    }

    /**
     * 修改员工账号状态
     */
    @Override
    public void updateEmployeeStatus(Integer status, Long id) {
        /*Employee e = Employee.builder().status(status).id(id).updateUser(BaseContext.getCurrentId())
                .updateTime(LocalDateTime.now()).build();*/
        Employee e = Employee.builder().status(status).id(id).build();
        employeeMapper.updateEmployee(e);
    }

    /**
     *根据id编辑员工信息接口
     */
    @Override
    public void updateEmployeeById(Employee e) {
        /*String token = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Long updateUser = claims.get("empId", Long.class);*/
        /*e.setUpdateTime(LocalDateTime.now());
        Long updateUser = BaseContext.getCurrentId();
        e.setUpdateUser(updateUser);*/
        employeeMapper.updateEmployee(e);
    }

    /**
     *修改员工密码信息接口
     */
    @Transactional
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        Employee e = employeeMapper.getById(BaseContext.getCurrentId());
        if (!e.getPassword().equals(DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes()))){
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        if (passwordEditDTO.getOldPassword().equals(passwordEditDTO.getNewPassword())){
            throw new PasswordErrorException("两次输入密码一样，你脑子瓦特了?");
        }
        e.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        employeeMapper.updateEmployee(e);
    }

}
